<template>
  <div class="m-page">
    <el-form
      class="m-card"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="部门状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="m-card m-margin-top">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:dept:add']"
          >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table
        class="m-margin-top table-scroll-one-search"
        header-cell-class-name="m-table-header"
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          prop="deptName"
          label="部门名称"
          width="260"
        ></el-table-column>
        <el-table-column
          prop="deptId"
          label="部门id"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          :formatter="statusFormat"
          width="100"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="200"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']"
            >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']"
            >新增</el-button
            >
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dept:remove']"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="deptList"
                :normalizer="normalizer"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                style="width: 100%"
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点类型" prop="type">
              <treeselect
                v-model="form.type"
                :options="nodeOptions"
                :normalizer="nodeNormalizer"
                placeholder="选择节点类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="form.type == 8">
            <el-col :span="12">
              <el-form-item label="标段号" prop="sectionNo ">
                <el-input v-model="form.sectionNo" placeholder="请输入标段号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="标段类型" prop="sectionType">
                <treeselect
                  v-model="form.sectionType"
                  :options="sectionTypeOptions"
                  :normalizer="nodeNormalizer"
                  placeholder="选择标段类型"
                />
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="12" v-if="form.type == 5">
            <el-form-item label="工程类型" prop="constructionType">
              <treeselect
                v-model="form.constructionType"
                :options="constructionOptions"
                :normalizer="nodeNormalizer"
                placeholder="选择工程类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == 10">
            <el-form-item label="工点类型" prop="pointType">
              <treeselect
                v-model="form.pointType"
                :options="pointTypeOptions"
                :normalizer="nodeNormalizer"
                placeholder="选择工点类型"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上级管理部门" prop="managerDeptSet">
              <treeselect
                v-model="form.managerDeptSet"
                :options="deptList"
                :normalizer="normalizer"
                flat
                multiple
                placeholder="选择上级管理部门"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="
              form.type == 5 ||
              form.type == 8 ||
              form.type == 9 ||
              form.type == 10
            "
          >
            <el-form-item label="施工单位" prop="constructionPart">
              <el-input
                v-model="form.constructionPart"
                placeholder="请输入标段号"
              />
            </el-form-item>
          </el-col>
          <template v-if="form.type == 10">
            <el-col :span="12">
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="form.longitude" placeholder="请输入经度" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="纬度" prop="latitude">
                <el-input v-model="form.latitude" placeholder="请输入纬度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上一工点" prop="preStation">
                <treeselect
                  v-model="form.preStation"
                  :options="deptTreeDeptData"
                  :normalizer="normalizer"
                  disable-branch-nodes
                  placeholder="选择上一工点"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下一工点" prop="nextStation">
                <treeselect
                  v-model="form.nextStation"
                  :options="deptTreeDeptData"
                  :normalizer="normalizer"
                  disable-branch-nodes
                  placeholder="选择下一工点"
                />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild,
  nodeTypeList, sectionTypeList, constructionTypeList, pointTypeList
} from '@/services/system/dept'
import { getDeptTreeDeptData } from '@/services/authorityManagement/managePersonnel'

export default Vue.extend({
  name: 'Dept',
  components: { Treeselect },
  data () {
    return {
      temporaryDeptId: '', // 临时
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 节点类型列表
      nodeOptions: [],
      // 标段类型列表
      sectionTypeOptions: [],
      // 工程类型
      constructionOptions: [],
      // 工点类型
      pointTypeOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      deptTreeDeptData: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      cascaderProps: {
        value: 'deptId',
        label: 'deptName',
        children: 'children'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '上级部门不能为空', trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' },
          { required: true, message: '显示排序不能为空', trigger: 'change' }
        ],
        type: [
          { required: true, message: '节点类型不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ]

      }
    }
  },
  created () {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    getDeptTreeDeptData().then(res => {
      this.deptTreeDeptData = res.data
    })
  },
  methods: {
    /** 查询部门列表 */
    getList () {
      this.loading = true
      listDept(this.queryParams).then((response) => {
        this.deptList = response.data
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    normalizer (node) {
      if (node.children === null || node.children === 'null') {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    nodeNormalizer (node) {
      return {
        id: node.dictValue,
        label: node.dictLabel
      }
    },
    // 字典状态字典翻译
    statusFormat (row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset()
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = '添加部门'
      this.getNodeTypeList()
      this.getConstructionTypeList()
      this.getSectionTypeList()
      this.getPointTypeList()
    },
    // 获取节点类型
    getNodeTypeList () {
      nodeTypeList().then((res) => {
        if (res.code === 200) {
          this.nodeOptions = res.data
        }
      })
    },
    // 获取工程类型
    getConstructionTypeList () {
      constructionTypeList().then((res) => {
        console.log(res, '工程类型')
        this.constructionOptions = res.data
      })
    },
    // 获取标段类型
    getSectionTypeList () {
      sectionTypeList().then((res) => {
        console.log(res, '标段类型')

        if (res.code === 200) {
          this.sectionTypeOptions = res.data
        }
      })
    },
    // 获取工点类型
    getPointTypeList () {
      pointTypeList().then((res) => {
        console.log(res, '工点类型')
        this.pointTypeOptions = res.data
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      getDept(row.deptId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改部门'
        this.temporaryDeptId = row.deptId
      })
      listDeptExcludeChild(row.deptId).then((response) => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
      this.getNodeTypeList()
      this.getConstructionTypeList()
      this.getSectionTypeList()
      this.getPointTypeList()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.managerDeptSet = this.form.managerDeptSet.filter(
            (v) => v !== this.temporaryDeptId
          )

          if (this.form.deptId !== undefined) {
            updateDept(this.form).then(() => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            console.log(this.form)
            // return
            addDept(this.form).then(() => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm(
        '是否确认删除名称为"' + row.deptName + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return delDept(row.deptId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
    }
  }
})
</script>
